package com.ddd.test.repoimpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ddd.test.aggregate.aggrorder.OrderEntity;
import com.ddd.test.dao.OrderMapper;
import com.ddd.test.dbo.OrderDO;
import com.ddd.test.repo.OrderRepo;
import com.ddd.test.utils.SnowFlakeGenerator;


@Component(value = "orderRepo")
public class OrderRepoImpl implements OrderRepo{
	  @Autowired
	  private OrderMapper orderMapper;

	  /**
	   * 
	   */
	  @Transactional
	  @Override
	  public void remove(OrderEntity orderEntity) {
		  orderMapper.deleteByOrderNumber(orderEntity.getOrderNumber());
	  }

	  /**
	   * 
	   */
	  @Transactional
	  @Override
	  public void add(OrderEntity orderEntity) {
		if (hasOrderEntity(orderEntity)) {
			orderMapper.updateByorderNumber(convert2OrderDO(orderEntity));
		}else {		
			orderMapper.insert(convert2OrderDO(orderEntity));
		}   
	  }
	  
	  @Override
	  public boolean hasOrderEntity(OrderEntity orderEntity) {
		OrderDO orderDO= orderMapper.selectByOrderNumber(orderEntity.getOrderNumber());
		if(orderDO != null) {
			return true;
		} else {
			return false;
		}
	  }

	//TODO
	  private OrderDO convert2OrderDO(OrderEntity orderEntity) {
		  OrderDO orderDO = orderMapper.selectByOrderNumber(orderEntity.getOrderNumber());
		  if(orderDO == null) {
			  orderDO = new OrderDO();
			  SnowFlakeGenerator snowFlakeGenerator = new SnowFlakeGenerator(1023);
			  orderDO.setId(snowFlakeGenerator.nextId());
			  orderDO.setOrderNumber(orderEntity.getOrderNumber());
		  }	  	  
		  orderDO.setCount(orderEntity.getCount());
		  orderDO.setPrice(orderEntity.getPrice());
		  orderDO.setProduct(orderEntity.getProduct());	  
		  orderDO.setSalesCode(orderEntity.getSalesCode());
		  return orderDO;
	  }
}
